import {connect} from 'react-redux'
import {toggleTodo,delTodo,VisibilityFilters} from "../Action/ActionTypes";
import TodoList from '../Components/TodoList'


/**
 * 根据filter类型过滤todos,并返回过滤后的todos
 * @param todos
 * @param filter
 * @returns {*}
 */
const getVisibleTodos = (todos,filter)=>{
    switch (filter){
        case VisibilityFilters.SHOW_COMPLETED:
            return todos.filter(todo => todo.completed)
        case VisibilityFilters.SHOW_ACTIVE:
            return todos.filter(todo => !todo.completed)
        case VisibilityFilters.SHOW_ALL:
        default:
            return todos
    }
}

// 1.注入state：VisibleTodoList 需要计算传到 TodoList 中的 todos，所以定义了根据 state.visibilityFilter 来过滤 state.todos 的方法.返回创建的新对象todos
const mapStateToProps = state=>({
    todos: getVisibleTodos(state.todos.present,state.visibilityFilter)
})

// 2.分发action：向展示组件TodoList注入toggleTodo,delTodo方法，并通过这些方法分发 TOGGLE_TODO,DEL_TODO 这些action
const mapDispatchToProps = dispatch=>{
    return {
        toggleTodo: index=>{
            dispatch(toggleTodo(index))
        },
        delTodo: index=>{
            dispatch(delTodo(index))
        }
    }
}

// 3.connect：从 Redux state 树中读取部分数据，并通过 props 来把这些数据提供给要渲染的组件
const VisibleTodoList = connect(
    mapStateToProps,
    mapDispatchToProps,
)(TodoList)

export default VisibleTodoList